package org.jeecg.glr.service.impl;

import com.google.gson.Gson;
import com.squareup.okhttp.*;
import org.jeecg.glr.domain.led.*;
import org.jeecg.glr.domain.led.fu.*;
import org.jeecg.glr.domain.led.opentask.OpenTaskDataDomain;
import org.jeecg.glr.domain.led.opentask.TaskData;
import org.jeecg.glr.entity.GlrLed;
import org.jeecg.glr.entity.GlrResource;
import org.jeecg.glr.service.ILedCommon;
import org.jeecg.glr.util.GLRConstant;
import org.jeecg.glr.util.GsonUtils;
import org.jeecg.glr.util.StringUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class LedCommon implements ILedCommon {

    @Value("${glr.path.ledServerPath}")
    private  String ledServerPath;

    @Value("${glr.path.projectPath}")
    private  String projectPath;
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    private static OkHttpClient client = new OkHttpClient();

    /**
     * 功能描述: HTTP 请求
     *
     * @param:
     * @return:
     * @auther: Administrator
     * @date: 2019/11/26 16:24
     */
    public static String post(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder().url(url).post(body).build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    /**
     * <p>开屏关屏</p>
     *
     * @param code
     * @param status
     * @return
     * @throws IOException
     * @author:Administrator 2019年6月26日
     * @update: [updatedate] [changer][change description]
     */
    public boolean OpenClose(String code, String status) {
        try {
            RequestDataOpenClose data = new RequestDataOpenClose();
            data.setFn(FuType.setScreenOpen);
            if (status.equals(GLRConstant.YN_Y)) {
                data.setArg1(true);
            } else {
                data.setArg1(false);
            }

            String jsonData = GsonUtils.toJsonString(data);
            String url = ledServerPath + code;
            String str = post(url, jsonData);
            Map<String, Object> map = GsonUtils.parseDataMap(str);
            return Boolean.parseBoolean(map.get("result").toString());
        } catch (IOException e) {
            return false;
        }
    }

    /**
     * 功能描述: 播放资源
     *
     * @param:
     * @return:
     * @auther: Administrator
     * @date: 2019/11/26 16:24
     */
    public boolean play(List<GlrLed> ledCodeList, List<GlrResource> resourcesList) throws Exception {
        String filePath = projectPath;

        for (GlrLed led : ledCodeList) {
            final String code = led.getCode();
            if (StringUtil.isNotEmpty(led.getStatus()) && !led.getStatus().equals(GLRConstant.YN_N)) {
                Gson gson = new Gson();
                int allSize = 0;
                int playTime = 0;
                int timeSpan = 15;
                List<Source> sources = new ArrayList<Source>();
                for (GlrResource resource : resourcesList) {
                    Source source = new Source();
                    source.setId(resource.getFileId());
                    source.setName(resource.getFileId());
                    source.set_type("Image");
                    source.set_id(UUID.randomUUID().toString());
                    source.setMd5(resource.getFileMd5());
                    source.setTop(0);
                    source.setPlayTime(playTime);
                    source.setTimeSpan(timeSpan);
                    source.setLeft(0);
                    source.setWidth(Integer.parseInt(led.getWidth()));
                    source.setHeight(Integer.parseInt(led.getHeight()));
                    allSize = (int) (allSize + resource.getFileSize());
                    source.setSize(resource.getFileSize());
                    sources.add(source);
                    playTime = playTime + 14;
                }
                List<Layer> layers = new ArrayList<Layer>();
                Layer layer = new Layer();
                layer.setSources(sources);
                layer.setRepeat(false);
                layers.add(layer);
                Program p = new Program();
                p.set_id(UUID.randomUUID().toString());
                p.setVersion(0);
                p.setTotalSize(allSize);
                p.setLayers(layers);
                p.setWidth(Integer.parseInt(led.getWidth()));
                p.setHeight(Integer.parseInt(led.getHeight()));
                List<TaskItem> items = new ArrayList<TaskItem>();
                TaskItem t = new TaskItem();
                t.set_id(UUID.randomUUID().toString());
                t.set_program(p);
                t.setRepeatTimes(1);

                List<Schedule> schedules = new ArrayList<Schedule>();
                Schedule schedule = new Schedule();
                schedule.setStartTime("00:00");
                schedule.setEndTime("23:59");
                schedule.setDateType(DateType.All);
                schedule.setTimeType(TimeType.Range);
                schedule.setFilterType(FilterType.None);
                schedules.add(schedule);
                t.setSchedules(schedules);
                items.add(t);
                ProgramsTask pt = new ProgramsTask();
                pt.set_id(UUID.randomUUID().toString());
                pt.setItems(items);
                PlayXixunTaskCommand px = new PlayXixunTaskCommand();
                px.set_type("PlayXixunTask");
                final String uuid = UUID.randomUUID().toString();
                px.setId(uuid);
                px.setTask(pt);
                px.setPreDownloadURL(filePath + GLRConstant.FILE_PATH_LED + led.getSysCompanyCode() + "/");
                px.setNotificationURL(projectPath + "/tBLedController.do?getByJSON");
                RequestData rd = new RequestData();
                rd.set_id(UUID.randomUUID().toString());
                rd.setCommand(px);
                final String jsonData = gson.toJson(rd);
                final String url = ledServerPath + led.getCode(); //check this

                LedCommon.post(url, jsonData);
            }
        }
        return true;
    }

    /**
     * <p>设置亮度</p>
     *
     * @param code
     * @param brightness
     * @return
     * @throws IOException
     * @author:Administrator 2019年6月26日
     * @update: [updatedate] [changer][change description]
     */
    public boolean setBrightness(String code, int brightness,Boolean disabledValue) throws IOException {
        Map<String, Object> map=null;
        if(disabledValue){
            RequestDataAutoBrightness data = new RequestDataAutoBrightness();
            data.setType("setAutoBrightness");
            String jsonData = GsonUtils.toJsonString(data);
            String url = ledServerPath + code;
            String str = post(url, jsonData);
            map = GsonUtils.parseDataMap(str);
            if(map.get("_type")!=null){
                if(map.get("_type").equals("success")){
                    return true;
                }
            }
            return false;
        }else{
            RequestDataBrightness data = new RequestDataBrightness();
            data.setFn(FuType.setBrightness);
            data.setArg1(brightness);
            String jsonData = GsonUtils.toJsonString(data);
            String url = ledServerPath + code;
            String str = post(url, jsonData);
            map = GsonUtils.parseDataMap(str);
            return Boolean.parseBoolean(map.get("result").toString());
        }

    }

    /**
     * <p>设置亮度</p>
     *
     * @param code
     * @return
     * @throws IOException
     * @author:Administrator 2019年6月26日
     * @update: [updatedate] [changer][change description]
     */
    public boolean getLedOpenStatus(String code) throws IOException {
        RequestDataLedStatus data = new RequestDataLedStatus();
        data.setFn(FuType.isScreenOpen);
        String jsonData = GsonUtils.toJsonString(data);
        String url = ledServerPath + code;
        String str = post(url, jsonData);
        Map<String, Object> map;
        try {
            map = GsonUtils.parseDataMap(str);
            return Boolean.parseBoolean(map.get("result").toString());
        } catch (Exception e) {
            return false;
        }

    }



    /**
     * 功能描述: 清空LED屏
     *
     * @param:
     * @return:
     * @auther: Administrator
     * @date: 2019/11/26 16:23
     */
    public boolean clearLed(String code) throws IOException {
        BaseRequest data = new BaseRequest();
        data.setType("clearPlayerTask");
        String jsonData = GsonUtils.toJsonString(data);
        String url = ledServerPath + code;
        String str = post(url, jsonData);
        Map<String, Object> map;
        try {
            map = GsonUtils.parseDataMap(str);
            return Boolean.parseBoolean(map.get("result").toString());
        } catch (Exception e) {
            return false;
        }

    }


    /**
     * <p>获取 网络类型</p>
     *
     * @param code
     * @return
     * @throws IOException
     * @author:Administrator 2019年6月26日
     * @update: [updatedate] [changer][change description]
     */
    public boolean getNetworkType(String code) throws IOException {
        RequestDataLedStatus data = new RequestDataLedStatus();
        data.setFn(FuType.getNetworkType);
        String jsonData = GsonUtils.toJsonString(data);
        String url = ledServerPath + code;
        String str = post(url, jsonData);
        Map<String, Object> map;
        try {
            map = GsonUtils.parseDataMap(str);
            if (map.get("result") != null) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }

    }

    /**
     * 功能描述: 设置定时任务
     *
     * @param:
     * @return:
     * @auther: Administrator
     * @date: 2019/11/26 16:23
     */
    public boolean setTaskTime(String code, String startTime, String endTime) {
        OpenTaskDataDomain domain = new OpenTaskDataDomain();
        boolean flag = false;
        List<org.jeecg.glr.domain.led.opentask.Schedule> schedules = new ArrayList<org.jeecg.glr.domain.led.opentask
                .Schedule>();
        org.jeecg.glr.domain.led.opentask
                .Schedule schedule = new org.jeecg.glr.domain.led.opentask
                .Schedule();
        schedule.setStartTime(startTime);
        schedule.setEndTime(endTime);
        schedule.setDateType(DateType.All);
        schedule.setTimeType(TimeType.Range);
        schedule.setFilterType(FilterType.None);

        List<Integer> weekFilter = new ArrayList<Integer>();
        List<Integer> monthFilter = new ArrayList<Integer>();
        schedule.setWeekFilter(weekFilter);
        schedule.setMonthFilter(monthFilter);
        schedules.add(schedule);
        TaskData task = new TaskData();
        task.setSchedules(schedules);
        domain.setTask(task);
        String jsonData = GsonUtils.toJsonString(domain);

        String url = ledServerPath + code;
        try {
            String str = post(url, jsonData);
            Map<String, Object> map;
            map = GsonUtils.parseDataMap(str);
            if (map.get("_type") != null) {
                if (map.get("_type").equals("success")) {
                    flag = true;
                }
            }
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 功能描述: 重启LED屏
     *
     * @param:
     * @return:
     * @auther: Administrator
     * @date: 2019/11/26 16:23
     */
    @Override
    public boolean restartLed(String code) throws IOException {
        RequestDataRestart data = new RequestDataRestart();
        data.setFn(FuType.reboot);
        String jsonData = GsonUtils.toJsonString(data);
        String url = ledServerPath + code;
        String str = post(url, jsonData);
        Map<String, Object> map;
        try {
            map = GsonUtils.parseDataMap(str);
            return Boolean.parseBoolean(map.get("result").toString());
        } catch (Exception e) {
            return false;
        }

    }


    /**
     * 功能描述:同步时间
     *
     * @param:
     * @return:
     * @auther: Administrator
     * @date: 2019/11/26 16:23
     */
    @Override
    public boolean syncTime(String code) throws IOException {
        RequestDataSyncTime data = new RequestDataSyncTime();
        data.setType("setTimeSync");
        data.setCardId(code);
        String jsonData = GsonUtils.toJsonString(data);
        String url = ledServerPath + code;
        String str = post(url, jsonData);
        Map<String, Object> map;
        try {
            map = GsonUtils.parseDataMap(str);
            if (map.get("result") != null) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }
    @Override
    public String getLedImgByCode(String code) throws IOException {
        RequestDataCcreenshot data = new RequestDataCcreenshot();
        data.setFn(FuType.screenshot);
        String jsonData = GsonUtils.toJsonString(data);
        String url = ledServerPath + code;
        String str = post(url, jsonData);
        Map<String, Object> map;
        try {
            map = GsonUtils.parseDataMap(str);
            if (map.get("result") != null) {
                return map.get("result").toString();
            }
        } catch (Exception e) {
           e.printStackTrace();
        }
        return null;
    }
}
